﻿using System;
using System.Collections.Generic;
using System.Text;
using Newtonsoft.Json;
using System.Data;

namespace Org.EasyWeb.Common
{
    public class DataSetConverter : JsonConverter
    {
        public override bool CanConvert(Type objectType)
        {
            return typeof(DataSet).IsAssignableFrom(objectType);
        }

        public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
        {
            DataSet ds = (DataSet)value;
            writer.WriteStartObject();
            foreach (DataTable dt in ds.Tables)
            {
                writer.WritePropertyName(dt.TableName);
                writer.WriteStartArray();
                foreach (DataRow dr in dt.Rows)
                {
                    writer.WriteStartObject();
                    foreach (DataColumn dc in dt.Columns)
                    {
                        writer.WritePropertyName(dc.ColumnName);
                        writer.WriteValue(dr[dc].ToString());
                    }
                    writer.WriteEndObject();
                }
                writer.WriteEndArray();
            }
            writer.WriteEndObject();
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            throw new NotImplementedException();
        }
    } 
}
